import React ,{useEffect, useState} from 'react';
import {DatePicker ,Space,Input ,ConfigProvider ,notification} from 'antd'
import {AppstoreOutlined ,PlusOutlined , ExportOutlined ,ClearOutlined ,SyncOutlined ,ExpandAltOutlined} from '@ant-design/icons'
import type { DatePickerProps, RangePickerProps } from 'antd/es/date-picker';
import 'dayjs/locale/zh-cn';
import './index.scss'
import locale from 'antd/es/locale/zh_CN';
import { useNavigate } from 'react-router-dom';
import CustomTable from '../../../../components/ccl/CustomTable';
import * as XLSX from 'xlsx'
import fs from 'file-saver'
import * as service from '../../../../api/ccl';


const SelectGoods = () => {
   
    const history = useNavigate()
    let [data,setData] = useState([])
    const { RangePicker } = DatePicker;
    const { Search } = Input;

    useEffect(()=>{
        selectList()
    },[])

    const selectList = async () => {
        const res = await service.selectchoose({page:1,limit:10})
        if(res.data.code == 200){
            setData(res.data.data.records)
        }
    }
    // 通过选择时间查询
    const onChange = async (
        value: DatePickerProps['value'] | RangePickerProps['value'],
        dateString: [string, string] | string,
      ) => {
        if(dateString != ''){
            const res = await service.findByTime({StartTime:dateString[0],EndTime:dateString[1]})
            if(res.data.code == 200){
                notification.success({message:'查询成功',duration:2})
                setData(res.data.data)
            }
        }
    };
   
    //   搜索
    const onSearch = async(value: string) => {
        if(value != ''){
            const newVal = value.toString()
            const res = await service.selectgoods({waybill:newVal,page:1,limit:5})
            if(res.data.code == 200){
                notification.success({message:'查询成功',duration:2})
                setData(res.data.data.records)
            }
        }
    };
    // 新增
    const toAdd = () => {
        history('/index/sale/addGoods')
    }

    // 导出文件
    let excelExport = (table:any,filename:any) => {
        const wb = XLSX.utils.table_to_book(table)
        const defaultCellStyle = {
            font:{name:'Verdana',sz:13,color:'FF00FF88'},
            fill:{fgColor:{rgb:'FFFFaa00'}}
        }
        const wopts:any = {
            bookType: 'xlsx',
            bookSST: false,
            type: 'binary',
            cellStyle: true,
            defaultCellStyle: defaultCellStyle,
            showGridLines: false,
        }
        // 生成xlsx格式的数据
        const wbout = XLSX.write(wb,wopts) 

        let data:any = [s2ab(wbout)]
        // 转换为2进制的Blob类型的数据
        const blob = new Blob(data,{type:'application/octet-stream'})
        
        // 文件另存为
        fs.saveAs(blob,filename + '.xlsx')
    }
    let s2ab = (s:any) => {
        if(typeof ArrayBuffer !== 'undefined'){
            const buf = new ArrayBuffer(s.length)
            const view = new Uint8Array(buf)
            for(let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
            return buf
        }else{
            const buf = new Array(s.length)
            for(let i = 0; i !== s.length;i++) buf[i] = s.charCodeAt(i) & 0xff;
            return buf
        }
    }
    const handexport = () => {
        let table = document.querySelector('table')
        excelExport(table,'download.xlsx')
    }

    // 删除
    const handClear = async  (record:any) => {  
        if(record.chooseWaybill != ''){
            const res = await service.selectdelete({waybill:record.chooseWaybill})
            if(res.data.code == 200){
                notification.success({message:"删除成功",description:2})
                let newData = JSON.parse(JSON.stringify(data))
                let i = newData.findIndex((item:any) => 
                    item.chooseCategory = record.chooseCategory)
                    if(i != -1){
                        newData.splice(i,1)
                    }
                    setData(newData)
                }
            }
    }

    // 刷新
    const handFlush = () => {
        history('/index/sale/selectgoods')
    }
    const clumns:any = [
        {
            title:'序号',
            key:'index',
            render:(_:any,__:any,index:any) =>index+1,
        },
        {
            title:'单号',
            key:'chooseWaybill',
            dataIndex: 'chooseWaybill',
        },
        {
            title:'客户',
            key:'chooseClient',
            dataIndex: 'chooseClient',
        },
        {
            title:'部门',
            key:'choosePartment',
            dataIndex: 'choosePartment',
        },
        {
            title:'状态',
            key:'chooseStatus',
            dataIndex: 'chooseStatus',
            filters: [
                {
                  text: '编辑',
                  value: '编辑',
                },
                {
                  text: '待审核',
                  value: '待审核',
                 
                },
                {
                  text: '已确认',
                  value: '已确认',
                 
                },
                {
                  text: '进行中',
                  value: '进行中',
                 
                },
                {
                  text: '已完成',
                  value: '已完成',
                
                },
              ],
            filterMode: 'tree',
            filterSearch: true,
            onFilter: (value: string, record :any) => 
                record.chooseStatus.indexOf(value) === 0,
        },
        {
            title:'成色',
            key:'chooseColor',
            dataIndex: 'chooseColor',
        },
        {
            title:'重量',
            key:'chooseWeight',
            dataIndex: 'chooseWeight',
        },
        {
            title:'数量',
            key:'chooseNum',
            dataIndex: 'chooseNum',
        },
        {
            title:'制单时间',
            key:'chooseTime',
            dataIndex: 'chooseTime',
        },
        {
            title:'操作',
            key:'操作',
            render:(record:any) => (
                <Space>
                    <ClearOutlined onClick={() => handClear(record) }/> 
                </Space>
            )
        },
    ]
    let newData = data.map((item:any,index:any) => ({
        key:index,
        index:item.chooseId,
        chooseWaybill:item.chooseWaybill,
        chooseCategory:item.chooseCategory,
        chooseWarehouse:item.chooseWarehouse,
        chooseListname:item.chooseListname,
        chooseClient:item.chooseClient,
        chooseStatus:item.chooseStatus,
        chooseTime:item.chooseTime,
        chooseColor:item.chooseColor,
        chooseNum:item.chooseNum,
        chooseWeight:item.chooseWeight,
        choosePartment:item.choosePartment

    }))
    
    return (
        <div className='seleectgoods'>
            <div className="header">
                <div className="header-left">
                    <div className="icon">
                        <AppstoreOutlined />
                        <span>黄金分类</span>
                    </div>
                    <div className="add" onClick={toAdd}>
                        <PlusOutlined />
                        <span>新增进货单</span>
                    </div>
                    <div className="export" onClick={handexport}>
                        <ExportOutlined />
                        <span>导出</span>
                    </div>
                </div>
                <div className="header-right">
                    <div className="time">
                        <Space direction="vertical" size={12}>
                        <ConfigProvider locale={locale}>
                            <RangePicker
                            format="YYYY-MM-DD"
                            onChange={onChange}
                            />
                         </ConfigProvider>
                        </Space>
                    </div>
                    <div className="search">
                        <Search
                        placeholder="请输入选货单号"
                        allowClear
                        enterButton="搜索"
                        onSearch={onSearch}
                        />
                        <div className="operation">
                        <SyncOutlined  onClick={handFlush}/>
                        <ExpandAltOutlined />
                    </div>
                    </div>
                    
                </div>
            </div>
            <div className="main">
                <CustomTable  data={newData } columns={clumns} />
            </div>
        </div>
    );
};

export default SelectGoods;